/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import { DAEMON_SERVER_LOCAL_HOST, DAEMON_SERVER_MIN_LISTEN_PORT } from '../const/daemon-const.js';
import { HvigorDaemonLogger } from '../log/hvigor-daemon-log.js';
import { tryUsePort } from '../util/port-util.js';

import { DaemonServerEventName, HvigorDaemonServer } from './hvigor-daemon-server.js';

const _log = HvigorDaemonLogger.getLogger('daemon');

export class DaemonServerLifecycle {
  /**
   * server启动并监听端口
   */
  async startListen(hvigorDaemonServer: HvigorDaemonServer) {
    const port = await tryUsePort(DAEMON_SERVER_MIN_LISTEN_PORT);
    if (port === -1) {
      const errMsg = 'hvigor daemon: No available port was found in the specified range';
      _log.debug(errMsg);
      hvigorDaemonServer.emit(DaemonServerEventName.LISTEN_FAILED, errMsg);
    } else {
      _log.debug(`hvigor daemon: Server start to listen. port=${port}`);
      hvigorDaemonServer.listen(port, DAEMON_SERVER_LOCAL_HOST);
    }
  }
}
